import jwt from 'jsonwebtoken';

// JWT配置
const JWT_SECRET = 'your-secret-key-change-in-production';
const ACCESS_TOKEN_EXPIRES = '15m'; // 访问令牌15分钟过期
const REFRESH_TOKEN_EXPIRES = '7d'; // 刷新令牌7天过期

// 存储刷新令牌（生产环境用Redis等存储）
const refreshTokenStore = new Map(); // key: refreshToken, value: { userId, phone }

// 生成token对
export const generateTokenPair = (userId, phone) => {
  const accessToken = jwt.sign(
    { userId, phone, type: 'access' },
    JWT_SECRET,
    { expiresIn: ACCESS_TOKEN_EXPIRES }
  );
  
  const refreshToken = jwt.sign(
    { userId, phone, type: 'refresh' },
    JWT_SECRET,
    { expiresIn: REFRESH_TOKEN_EXPIRES }
  );
  
  // 存储刷新令牌
  refreshTokenStore.set(refreshToken, { userId, phone });
  
  return {
    accessToken,
    refreshToken,
    expiresIn: 15 * 60 // 15分钟，单位：秒
  };
};

// 验证访问令牌中间件
export const verifyAccessToken = (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ message: '缺少访问令牌' });
  }
  
  const token = authHeader.substring(7);
  
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    if (decoded.type !== 'access') {
      return res.status(401).json({ message: '无效的令牌类型' });
    }
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(401).json({ message: '访问令牌无效或已过期' });
  }
};

// 获取刷新令牌存储
export const getRefreshTokenStore = () => refreshTokenStore;

// 验证刷新令牌
export const verifyRefreshToken = (refreshToken) => {
  try {
    const decoded = jwt.verify(refreshToken, JWT_SECRET);
    if (decoded.type !== 'refresh') {
      return null;
    }
    
    const storedToken = refreshTokenStore.get(refreshToken);
    if (!storedToken) {
      return null;
    }
    
    return decoded;
  } catch (error) {
    return null;
  }
};